const MainCategory = require('../entity/category/maincategory');

const Client = require('../module/const/Client');
const ProductCategory = require('../entity/product/productcategory');

// 分类列表
async function categoryList (client, areaId) {
    const pipeline = [{
        $match: { areaId: MainCategory.toObjectId(areaId) }
    }, {
        $sort: { sort: -1 }
    }];
    if (client === Client.MiniProgram) {
        pipeline.push({
            $match: { isEnable: true }
        });
    }
    pipeline.push({
        $lookup: {
            from: 'sub_category',
            localField: '_id',
            foreignField: 'mainCategoryId',
            as: 'subCategory'
        }
    });
    const MainCategoryModel = new MainCategory().getModel();
    return MainCategoryModel.aggregate(pipeline);
}

// 查找对应关系产品
/**
 * 查找对应关系产品
 * @param areaId
 * @param mainCategoryId
 * @param subCategoryId
 * @returns {Promise<*>}
 */
async function correspondingProduct (areaId, mainCategoryId, subCategoryId) {
    const productCategoryEntity = new ProductCategory();
    const productCategoryModel = productCategoryEntity.getModel();
    const productData = await productCategoryModel.aggregate([
        {
            $match: {
                areaId: ProductCategory.toObjectId(areaId),
                subCategoryId: ProductCategory.toObjectId(subCategoryId),
                mainCategoryId: ProductCategory.toObjectId(mainCategoryId)
            }
        },
        {
            $lookup: {
                from: 'product',
                localField: 'productId',
                foreignField: '_id',
                as: 'product'
            }
        },
        {
            $unwind: {
                path: '$product',
                preserveNullAndEmptyArrays: true
            }
        },
        {
            $match: {
                'product.isDelete': false
            }
        }

    ]);
    return productData.map(item => item.product).sort((a, b) => b.sort - a.sort);
}

module.exports = {
    categoryList,
    correspondingProduct
};
